package rsj.dao;

import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import rsj.db.dbutils.UniqueID;
import rsj.domain.ProdUpListQuery;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ProdUpDao extends BaseDao {

    private static final ProdUpDao instance = new ProdUpDao();
    private static final String table_name = "sys.sys_prou";
    private static final String allColumns = "prou_id,prou_prod_id,prou_utime,prou_docid,prou_docname";

    public static ProdUpDao getInstance() {
        return instance;
    }

    public TableNode getUpPro(ProdUpListQuery query) {
        String sqlTemp = "SELECT * FROM sys.sys_prou prou where prou.prou_prod_id = ? ORDER BY prou.prou_utime DESC LIMIT %s OFFSET %s";
        String sql = String.format(sqlTemp, query.getLimit(), query.getOffset());
        return (TableNode) invokeSql(conn -> {
            return getQueryRunner().queryLinkTableNode(conn, sql, query.getProd_Id());
        });
    }

    public int getUpProTotalSize(ProdUpListQuery query) {
        String sql = "SELECT count(prou_id) FROM sys.sys_prou prou where prou.prou_prod_id = ?";
        return (int) invokeSql(conn -> {
            Node node = getQueryRunner().queryLinkNode(conn, sql, query.getProd_Id());
            return node.valueInt();
        });
    }

    public String insert(String prod_id, String prod_docid, String prod_docname) {
        String sql = String.format(insertSql, table_name, allColumns, "?,?,to_date(?,'YYYY-MM-dd'),?,?");
        String id = String.valueOf(UniqueID.generateId());
        invokeSql(conn -> {
            return getQueryRunner().update(conn, sql, id, prod_id
                    , new SimpleDateFormat("yyyy-MM-dd").format(new Date()), prod_docid, prod_docname);
        });

        return id;
    }
}
